<template>
  <div class="container">
    <div class="app-container">
      <!-- 添加角色按钮 -->
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="addRole">添加角色</el-button>
      </div>
      <!-- table组件 -->
      <div>
        <el-table :data="data">
          <el-table-column label="角色" prop="name" align="center">
            <!-- 使用row中的isEdit属性判断是否为编辑 -->
            <template v-slot="{row}">
                <input v-if="row.isEdit" type="text" size="mini" v-model="row.editRow.name">
                <span v-else>{{row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="启动" prop="state" align="center">
            <!-- 利用插槽转换数据 -->
            <template v-slot="{row}">
              <!-- 使用row中的isEdit属性判断是否为编辑 -->
              <el-switch v-if="row.isEdit" :active-value="1" :inactive-value="0" v-model="row.editRow.state"></el-switch>
              <span>{{row.state ===1 ? "已启动": row.state===0? "未启用":"无"  }}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="description" align="center">
            <template v-slot="{row}">
                <input v-if="row.isEdit" type="textarea" size="mini" v-model="row.editRow.description" />
                <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <!-- 利用插槽操作数据 -->
            <template v-slot="{row}">
                <!-- 使用row中的isEdit属性判断是否为编辑 -->
              <template v-if="row.isEdit">
                <el-button size="mini" @click =btnEditOk(row)>确认</el-button>
                <el-button size="mini" @click="row.isEdit = false">取消</el-button>
              </template>
            
              <template v-else>
                <el-button size="mini" type="text" @click="btnPermissions(row.id)">分配权限</el-button>
                <el-button size="mini" @click="editData(row)" type="text">编辑</el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm=deleteRole(row.id)>
                  <el-button size="mini" slot="reference" style="margin-left: 10px;" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div>
        <el-row type="flex" justify ="end" align="middle" style="height:60px">
          <el-pagination layout="total, prev, pager, next" 
          :total="this.pageParams.total"
          :page-size="this.pageParams.pagesize"
          :current-page="this.pageParams.page"
          @current-change="changePage"></el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 添加权限弹框-->
    <el-dialog :visible.sync="showDialog" title="添加角色" width="500px" @close = "this.btnCenter">
      <el-form ref="addFrom" :model="addFrom" :rules="addRules" label-width="120px">
        <el-form-item label="角色名称:" prop="name">
          <el-input placeholder="请输入角色名称" v-model="addFrom.name"  size="mini" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="启动:" prop="state">
          <el-switch v-model="addFrom.state" :active-value="1" :inactive-value="0" size="mini"></el-switch>
        </el-form-item>
        <el-form-item label="角色描述:" prop="name">
          <el-input  type="textarea" placeholder="角色描述" v-model="addFrom.description" :rows="3"  size="mini" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="btnOk">确认</el-button>
          <el-button @click="btnCenter">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog :visible.sync="showDialogPermission" width="500px" title="分配权限">
      <el-tree :data="permissionData"
                show-checkbox
               :props="defaultProps"
               :default-checked-keys="permIds"
               node-key="id"
               ref="permTree">
      </el-tree>
      <el-row >
              <el-col type="flex" align="middle" justify="center">
                <el-button type="primary" @click="btnPermissionOk">确认</el-button>
                <el-button @click="btnPermissionCenter" >取消</el-button>
              </el-col>
            </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {getRoleList,addRole ,updateRole,deleteRole,getRoleDetails,updatePermission} from '@/api/role'
import {transListToTreeData} from '@/utils/index'
import {getPermissionList} from '@/api/permission'
export default {
  name: 'Role',
  data(){
    return{
      //表格的数据
      data:[],
      //页面
      pageParams:{
        page:1,
        pagesize:5,
        total: 0
      },
      //控制添加的按钮
      showDialog: false,
      //表单数据
      addFrom:{
        name:'',
        state:0,
        description:'',
      },
      //表单的验证规则
      addRules:{
        name:[{required:true,message:'请输入角色名称',trigger: 'blur'}],
        description:[{required:true,message:'请输入角色描述',trigger: 'blur'}]
      },
      //分配权限展示弹框
      showDialogPermission:false,
      //分配权限的集合
      permissionData:[],
      //绑定数据
      defaultProps:{
        label:'name',
        children:'children'
      },
      //权限选择的数据
      permIds:[],
      //当前角色id
      currentRoleId: null
    }
  },
  methods:{
    //获取角色
    async getRoleList(){
     const {rows ,total} =  await getRoleList(this.pageParams)
     this.data = rows
     this.pageParams.total = total
     this.data.forEach((item)=>{
      this.$set(item, 'isEdit', false)
      this.$set(item,'editRow',{
          name: item.name,
          state: item.state,
          description: item.description
        })
     })
    },
    // 切换分页时 请求新的数据
    changePage(newPage){
      this.pageParams.page = newPage
      this.getRoleList()
    },
    //添加角色
    addRole(){
      this.showDialog=true
    },
    //弹框提交按钮
    btnOk(){
      this.$refs.addFrom.validate(async(isOk)=>{
        if(isOk){
         const result =  await addRole(this.addFrom)
         this.getRoleList()
         this.$message.success(result.message)
         this.btnCenter()
        }
      })
    },
    btnCenter(){
      this.showDialog= false
      this.$refs.addFrom.resetFields()
    },
    //编辑
    editData(row){
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    //编辑确认按钮
    async btnEditOk(row){
      if(row.editRow.name && row.editRow.description){
        // 后端更新
        await updateRole({...row.editRow,id:row.id})
        this.$message.success("更新成功")
        //前端数据跟新
        Object.assign(row,{...row.editRow,isEdit:false})
      }else{
        this.$message.warning("角色名称和角色描述不能为空")
      }
    },
    //删除
    async deleteRole(id){
      console.log(id)
      await deleteRole(id)
      this.$message.success('删除成功')
      if(this.data.length===1){
        this.pageParams.page--
      }
      this.getRoleList()
    },
    //分配权限的弹框
    async btnPermissions(id){
      this.showDialogPermission =true
      this.permissionData= transListToTreeData(await getPermissionList(),0)
      const {permIds} =  await getRoleDetails(id)
      this.currentRoleId = id
      this.permIds = permIds
    },
    //分配权限的确认按钮
    async btnPermissionOk(){
     await updatePermission({
      id:this.currentRoleId,
      permIds:this.$refs.permTree.getCheckedKeys()
     })
     this.$message.success('分配权限成功')
     this.btnPermissionCenter()
    },
    //分配权限的取消按钮
    btnPermissionCenter(){
      this.showDialogPermission =false
    }
  },
  created(){
    this.getRoleList()
  }
}
</script>
<style scoped>
.role-operate{
  padding: 10px;
}
</style>
